package org.dromara.yuanshidian.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.commons.math3.stat.descriptive.rank.Min;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.MimeTypeUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.dromara.yuanshidian.domain.bo.*;
import org.dromara.yuanshidian.domain.vo.Ab01Vo;
import org.dromara.yuanshidian.domain.vo.Ab02Vo;
import org.dromara.yuanshidian.domain.vo.ExportAb04Vo;
import org.dromara.yuanshidian.service.*;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.yuanshidian.domain.vo.Ab04Vo;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 原人员账户明细(缴费明细)
 *
 * @author TzhongTop
 * @date 2025-01-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/yuanshidian/ab04")
public class Ab04Controller extends BaseController {

    private final IAb04Service ab04Service;

    private final IExamineDataService examineDataService;

    private final ISysOssService ossService;

    private final IAb05Service ab05Service;

    private final IAb02Service ab02Service;


    private final IAb04RefundService ab04RefundService;

    /**
     * 查询原人员账户明细(缴费明细)列表
     */
    //@SaCheckPermission("yuanshidian:ab04:list")
    @GetMapping("/list")
    public TableDataInfo<Ab04Vo> list(Ab04Bo bo, PageQuery pageQuery) {
        return ab04Service.queryPageList(bo, pageQuery);
    }

    /**
     * 导出原人员账户明细(缴费明细)列表
     */
    @SaCheckPermission("yuanshidian:ab04:export")
    @Log(title = "原人员账户明细(缴费明细)", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(Ab04Bo bo, HttpServletResponse response) {
        List<Ab04Vo> list = ab04Service.queryList(bo);
        ExcelUtil.exportExcel(list, "原人员账户明细(缴费明细)", Ab04Vo.class, response);
    }

    /**
     * 人员信息确认表导出
     */
    @SaCheckPermission("yuanshidian:ab04:exportab04ry")
    @Log(title = "人员信息确认表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportab04ry")
    public void exportab04ry(Ab02Bo bo, HttpServletResponse response) {
        if(bo.getSplitID() !=null && !bo.getSplitID().isEmpty()){
            String[] splitID = bo.getSplitID().split(",");
            List<Ab02Vo> list = ab02Service.exportAb02(bo, splitID);
            Map<String, String> map = new HashMap<>();
            map.put("dw01", bo.getDw01());
            map.put("dw02", bo.getDw02());
            Map<String, Object> multiListMap = new HashMap<>();
            multiListMap.put("map", map);
            multiListMap.put("data1", list);
            ExcelUtil.exportTemplateMultiList(multiListMap, "人员信息确认表.xlsx", "excel/人员信息确认表.xlsx", response);
        }else {
            List<Ab02Vo> list = ab02Service.queryAb02List(bo);
            Map<String, String> map = new HashMap<>();
            map.put("dw01", bo.getDw01());
            map.put("dw02", bo.getDw02());
            Map<String, Object> multiListMap = new HashMap<>();
            multiListMap.put("map", map);
            multiListMap.put("data1", list);
            ExcelUtil.exportTemplateMultiList(multiListMap, "人员信息确认表.xlsx", "excel/人员信息确认表.xlsx", response);

        }
    }

    /**
     * 试点期间参保人员缴费确认表导出
     */
    @SaCheckPermission("yuanshidian:ab04:exportab04jf")
    @Log(title = "试点期间参保人员缴费确认表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportab04jf")
    public void exportab04jf(Ab02Bo bo, HttpServletResponse response) {
        if(bo.getSplitID() !=null && !bo.getSplitID().isEmpty()){
            String[] splitID = bo.getSplitID().split(",");
            List<Ab02Vo> list = ab02Service.exportAb02(bo, splitID);
            Map<String, String> map = new HashMap<>();
            map.put("dw01", bo.getDw01());
            map.put("dw02", bo.getDw02());
            Map<String, Object> multiListMap = new HashMap<>();
            multiListMap.put("map", map);
            multiListMap.put("data1", list);
            ExcelUtil.exportTemplateMultiList(multiListMap, "试点期间参保人员缴费确认表.xlsx", "excel/试点期间参保人员缴费确认表.xlsx", response);
        }else {
            List<Ab02Vo> list = ab02Service.queryAb02List(bo);
            Map<String, String> map = new HashMap<>();
            map.put("dw01", bo.getDw01());
            map.put("dw02", bo.getDw02());
            Map<String, Object> multiListMap = new HashMap<>();
            multiListMap.put("map", map);
            multiListMap.put("data1", list);
            ExcelUtil.exportTemplateMultiList(multiListMap, "试点期间参保人员缴费确认表.xlsx", "excel/试点期间参保人员缴费确认表.xlsx", response);

        }
    }


    /**
     * 试点期间参保人员退费确认表导出
     */
    @SaCheckPermission("yuanshidian:ab04:exportab04tf")
    @Log(title = "试点期间参保人员退费确认表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportab04tf")
    public void exportab04tf(Ab02Bo bo, HttpServletResponse response) {
        if(bo.getSplitID() !=null && !bo.getSplitID().isEmpty()){
            String[] splitID = bo.getSplitID().split(",");
            List<Ab02Vo> list = ab02Service.exportAb02(bo, splitID);
            Map<String, String> map = new HashMap<>();
            ExcelUtil.exportTemplate(CollUtil.newArrayList(map, list), "试点期间参保人员退费确认表.xlsx", "excel/试点期间参保人员退费确认表.xlsx", response);
            //ExcelUtil.exportExcel(list, "试点期间参保人员退费确认表", ExportAb04Vo.class, response);
            //ab02Service.updateAb02(splitID);
            //ab04Service.updateAb04(splitID);
        }else {
            List<Ab02Vo> list = ab02Service.queryAb02List(bo);
            Map<String, String> map = new HashMap<>();
            ExcelUtil.exportTemplate(CollUtil.newArrayList(map, list), "试点期间参保人员退费确认表.xlsx", "excel/试点期间参保人员退费确认表.xlsx", response);

        }
    }

    /**
     * 获取原人员账户明细(缴费明细)详细信息
     *
     * @param ID 主键
     */
    @SaCheckPermission("yuanshidian:ab04:query")
    @GetMapping("/{ID}")
    public R<Ab04Vo> getInfo(@NotNull(message = "主键不能为空")
                             @PathVariable Long ID) {
        return R.ok(ab04Service.queryById(ID));
    }

    /**
     * 新增原人员账户明细(缴费明细)
     */
    @SaCheckPermission("yuanshidian:ab04:add")
    @Log(title = "原人员账户明细(缴费明细)", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@RequestBody Ab04Bo bo) {
             return toAjax(ab04Service.insertByBo(bo));
    }

    /**
     * 修改原人员账户明细(缴费明细)
     */
    @SaCheckPermission("yuanshidian:ab04:edit")
    @Log(title = "原人员账户明细(缴费明细)", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody Ab04Bo bo) {
        return toAjax(ab04Service.updateByBo(bo));
    }

    /**
     * 批量删除原人员账户明细(缴费明细)
     * 逻辑删除：将指定ID列表的记录DelStatus更新为1
     *
     * @param ids 主键ID列表(多个ID用逗号分隔)
     */
    @SaCheckPermission("yuanshidian:ab04:remove")
    @Log(title = "原人员账户明细(缴费明细)", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch/{ids}")
    public R<Void> removeBatch(@NotNull(message = "主键列表不能为空") @PathVariable String ids
    ) {
        // 将逗号分隔的ID字符串转换为Long列表
        List<Long> idList = Arrays.stream(ids.split(","))
            .map(Long::valueOf)
            .collect(Collectors.toList());

        // 调用批量更新方法（需在Service层实现）
        int updateCount = ab04Service.batchUpdateDelStatus(idList);

        return toAjax(updateCount);
    }

    /**
     * 缴费明细提交审核
     */
    @SaCheckPermission("yuanshidian:ab04:submit")
    @Log(title = "缴费明细审核接口", businessType = BusinessType.UPDATE)
    @GetMapping("/submit/{ID}")
    public R<Void> submit(@NotNull(message = "主键不能为空") @PathVariable Long ID) {
        Ab04Bo ab04Bo = new Ab04Bo();
        ab04Bo.setId(ID);
        ab04Bo.setStatus(2L);
        return toAjax(ab04Service.updateByBo(ab04Bo));
    }

    /**
     * 缴费明细强制驳回
     */
    @SaCheckPermission("yuanshidian:ab04:turndown")
    @Log(title = "缴费明细驳回接口", businessType = BusinessType.UPDATE)
    @GetMapping("/turndown/{ID}")
    public R<Void> turndown(@NotNull(message = "主键不能为空") @PathVariable Long ID ) {
        Ab04Bo ab04Bo = new Ab04Bo();
        ab04Bo.setId(ID);
        ab04Bo.setStatus(1L);
        return toAjax(ab04Service.updateByBo(ab04Bo));
    }

    /**
     * 缴费明细据审批
     */
    @SaCheckPermission("yuanshidian:ab04:examine")
    @Log(title = "缴费明细数据审批", businessType = BusinessType.UPDATE)
    @PostMapping("/examine")
    public R<Void> examine(@Validated(EditGroup.class) @RequestBody ExamineDataBo examineDataBo) {
        Ab04Bo ab04Bo = new Ab04Bo();
        ab04Bo.setId(examineDataBo.getExaminedataId());
        if (examineDataBo.getExamineStatus() == 1) {
            ab04Bo.setStatus(3L);
            examineDataBo.setExamineName(LoginHelper.getUsername());
            examineDataBo.setExamineDate(new Date());
            examineDataService.insertByBo(examineDataBo);
            return toAjax(ab04Service.updateByBo(ab04Bo));
        } else {
            ab04Bo.setStatus(4L);
            examineDataBo.setExamineName(LoginHelper.getUsername());
            examineDataBo.setExamineDate(new Date());
            examineDataService.insertByBo(examineDataBo);
            ab04Service.updateByBo(ab04Bo);
            return R.fail(500, "审核数据不通过被驳回");
        }
    }

    /**
     * 附件上传
     */
    @SaCheckPermission("yuanshidian:ab04:ab04upload")
    @RepeatSubmit
    @Log(title = "附件上传", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/ab04upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> ab04upload(@RequestParam("file") MultipartFile file, @RequestParam("ID") Long ID) throws Exception {
        if (!file.isEmpty()) {
            String extension = FileUtil.extName(file.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION) + "格式");
            } else {
                SysOssVo oss = ossService.upload(file);
                Ab04Bo ab04Bo = new Ab04Bo();
                ab04Bo.setId(ID);
                ab04Bo.setFileurl(oss.getUrl());
                return toAjax(ab04Service.updateByBo(ab04Bo));
            }
        }
        return R.fail("上传文件异常，请重新上传");
    }
    /**
     * 批量导入Excel数据
     */
    @PostMapping("/import")
    public R<String> importExcel(@NotNull(message = "导入文件不能为空") @RequestParam("file") MultipartFile file
    ) throws IOException {
        // 1. 校验文件格式
        String filename = file.getOriginalFilename();
        if (filename == null || (!filename.endsWith(".xlsx") && !filename.endsWith(".xls"))) {
            return R.fail("请上传Excel格式文件（.xlsx或.xls）");
        }

        // 2. 读取Excel数据
        List<Ab04ExcelDTO> excelList = EasyExcel.read(file.getInputStream())
            .head(Ab04ExcelDTO.class)
            .sheet() // 读取第一个sheet
            .doReadSync(); // 同步读取（小文件适用，大文件建议用监听器异步）

        if (CollectionUtils.isEmpty(excelList)) {
            return R.fail("Excel文件中未读取到数据");
        }

        // 3. 调用服务层处理导入
        return ab04Service.batchImport(excelList);
    }

    /**
     * 下载Excel导入模板
     */
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 1. 设置响应头（指定下载文件类型、文件名）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("缴费明细导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
        // 2. 用EasyExcel生成模板（写入表头+1行示例数据）
        EasyExcel.write(response.getOutputStream(), Ab04ExcelDTO.class)
            .sheet("缴费明细导入模板") // 工作表名称
            .doWrite(() -> {
                // 生成1行示例数据（用于用户参考）
                Ab04ExcelDTO example = new Ab04ExcelDTO();
                example.setAaa027("330100");
                example.setDw01("D00123");
                example.setDw02("系统自动成测试据用于参考-正式数据填入前请务必删除！！！");
                example.setGr03("GR00123456");
                example.setGr04("张三");
                example.setGr02("330106199001011234");
                example.setGrmx01("1");
                example.setGrmx02("202401");
                example.setGrmx03(new java.util.Date()); // 实际示例可填2024-01-15
                example.setGr18(new java.math.BigDecimal("8000.00"));
                example.setGr19(4500L);
                example.setGr20(new java.math.BigDecimal("360.00"));
                example.setGrmx04(new java.math.BigDecimal("180.00"));
                example.setGrmx05(new java.math.BigDecimal("0.00"));
                example.setDw14(6000L);
                example.setCs03(8L);
                example.setDw68("1");
                example.setGrjx01("2023");
                example.setJfStarttime(new java.util.Date());
                example.setJfEndtime(new java.util.Date());
                example.setGr01("330106199001011234");
                example.setJsStartmonth("202401");
                example.setJsEndmonth("202412");
                example.setJfPaymentmonths(12L);
                example.setGrjfbx(new java.math.BigDecimal("4320.00"));
                example.setGrzhbx(new java.math.BigDecimal("5400.00"));
                example.setJfssfbz("2");
                return java.util.Collections.singletonList(example);
            });
    }


    /**
     * 批量--计算用户每年的缴费金额、利息收入
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/calculateSocialCost", method = RequestMethod.GET)
    public R<Void> calculateSocialCost(HttpServletRequest request, HttpServletResponse response) {
        ab04Service.calculateSocialCost();
        return R.ok();
    }

    /**
     * 根据个人账号计算用户每年的缴费金额以及利息收入
     * @param gr03
     * @param
     * @return
     */
    @RequestMapping(value = "/calculateSocialCostGr03", method = RequestMethod.GET)
    public R<Void>  calculateSocialCostGr03(HttpServletRequest request, HttpServletResponse response,String gr03) {
        if(gr03==null || gr03.equals("")){
            R.fail("个人账号不能为空，否则无法进行计算!");
        }
        ab04Service.calculateSocialCostGr03(gr03);
        return R.ok();
    }
}
